<template>
  <!-- 新增或修改数据 -->
  <el-dialog :visible.sync="dialogFormVisible">
    <!-- 输入框 -->
    <el-form
      :model="ruleForm"
      status-icon
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <!-- 标题 -->
      <el-form-item label="标题" prop="name">
        <el-input
          type="text"
          autocomplete="off"
          v-model="ruleForm.name"
        ></el-input>
      </el-form-item>
      <!-- 图片 -->
      <el-form-item label="图片" prop="img">
        <div class="file" @click="openFile">
          <img
            v-if="ruleForm.img"
            :src="ruleForm.img"
            style="width: 100px; height: 100px"
          />
          <div v-else>+</div>
        </div>
        <input
          id="file"
          @change="changeFile"
          style="display: none"
          type="file"
          accept="image/*"
        />
      </el-form-item>
      <!-- 按钮 -->
      <el-form-item style="margin-top: 10px">
        <el-button type="primary" @click="submit">提交</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import api from "../../../api/index";
export default {
  name: "categoryBrandEditer",
  components: {},
  data() {
    return {
      category: [], //当前分类
      categoryList: [], //所有分类
      row: [],
      brands: [],
      dialogFormVisible: false,
      ruleForm: {
        name: "",
        img: "",
        form: "brand",
      },
      rules: {
        name: { required: true, message: "标题不能为空", trigger: "blur" },
        img: { required: true, message: "图片不能为空", trigger: "blur" },
      },
    };
  },
  methods: {
    openFile() {
      let fileElement = document.getElementById("file");
      fileElement.click();
    },
    changeFile(e) {
      let files = e.target.files;
      let formData = new FormData();
      formData.append("file", files[0]);
      this.$http({
        url: "/upload",
        method: "POST",
        data: formData,
      }).then((res) => {
        if (res.path) this.ruleForm.img = api.baseURL + "/" + res.path;
        this.ruleForm.img = this.ruleForm.img.replaceAll("\\", ("\\\\\\\\"));
      });
    },
    add() {
      this.ruleForm = {
        form: "brand",
      };
      this.dialogFormVisible = true;
    },
    //数组克隆独立控制
    deepClone(obj) {
      const objClone = Array.isArray(obj) ? [] : {};
      if (obj && typeof obj === "object") {
        for (var key in obj) {
          if (Object.prototype.hasOwnProperty.call(obj, key)) {
            // 用for...in循环会获取到原型链上的可枚举属性，不过可以使用hasOwnProperty()方法过滤掉。
            if (obj[key] && typeof obj[key] === "object") {
              // 判断ojb子元素是否存在并且是否为为对象，如果是，递归复制
              objClone[key] = this.deepClone(obj[key]);
            } else {
              // 如果不是，简单复制
              objClone[key] = obj[key];
            }
          }
        }
      }
      return objClone;
    },
    //编辑
    edit(row) {
      this.category = [];
      this.row = row;
      //点击编辑时，通过当前的_id查询所属分类
      this.getCategory(row._id);
      this.ruleForm = {};
      this.dialogFormVisible = true;
      this.ruleForm = this.deepClone(row);
      this.ruleForm.form = "brand";
      this.ruleForm.indexId = row._id;
    },
    //新增或者修改
    submit() {
      let indexId = this.ruleForm.indexId;
      this.$refs.ruleForm.validate((valid) => {
        if (this.ruleForm.img)
          this.ruleForm.img = this.ruleForm.img.replaceAll("\\", ("\\\\\\\\"));
        if (valid) {
          this.$http({
            url: indexId ? "/admin/change" : "/admin/addBrand",
            method: indexId ? "PUT" : "POST",
            data: this.ruleForm,
          }).then((res) => {
              if (!res.errorMsg) {
                this.$emit("load", indexId ? undefined : 1);
                this.dialogFormVisible = false;
                this.$message({
                  type: "success",
                  message: "数据处理成功",
                });
              }
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //获取品牌
    getBrand() {
      this.$http({
        url: "/admin/getBrand",
      }).then((res) => {
        this.brands = res;
      });
    },
    //创建时获取多选栏的属性
    getCategoryList() {
      this.$http({
        url: "/admin/getCategoryList",
      }).then((res) => {
        this.categoryList = res;
      });
    },

    //根据商品Id查询他所属的分类
    getCategory(productId) {
      this.$http({
        url: "/admin/getCategory",
        params: { productId },
      }).then((res) => {
        for (let i = 0; i < res.length; i++) {
          this.category.push(res[i].categoryId);
        }
        console.log(this.category);
        console.log(this.categoryList);
      });
    },
  },
  created() {
    this.getCategoryList();
    this.getBrand();
  },
  mounted() {},
};
</script>
  
<style scoped>
.form {
  margin-left: 80px;
  margin-top: 50 px;
}
.searchContent {
  display: flex;
  height: 80px;
  line-height: 80px;
  width: 600px;
}
.title {
  margin-right: 10 px;
  width: 80px;
  text-align: center;
}
.button {
  margin-left: 30px;
  width: 50px;
  height: 30px;
}

.file {
  text-align: center;
  line-height: 100px;
  width: 100px;
  height: 100px;
  border: #ccc 1px dashed;
}
</style>